package com.axonactive.yolo.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.axonactive.yolo.domain.ExchangeRate;
import com.axonactive.yolo.service.interfaces.ExchangeRateService;
import com.axonactive.yolo.util.CONSTANTS;
import com.axonactive.yolo.util.session.SessionHelper;

@Controller
public class ExchangeRatesController {
	
	Logger logger = Logger.getLogger(ExchangeRatesController.class);

	@Autowired
	private ExchangeRateService exchangeRateService;

	// Get all currency codes to return for client (see in jscurrency.jsp)
	@RequestMapping(value = { "/latest_exchange_rates" }, method = RequestMethod.GET)
	@ResponseBody
	public String getLatestExchangeRates(HttpSession session) throws JsonGenerationException, JsonMappingException, IOException{
		ObjectMapper objectMapper = new ObjectMapper();
		String rates = objectMapper.writeValueAsString(exchangeRateService.findAll());
		if(SessionHelper.getExchangeRates(session).equals("")){
			SessionHelper.setExchangeRates(session, rates);
		}
		return rates;
	}

	// Show rates table when click link at footer
	@RequestMapping(value = { "/exchange_rates" }, method = RequestMethod.GET)
	public ModelAndView showExchangeRates(HttpSession session) throws Exception {
		String currencyCode = SessionHelper.getCurrencyCode(session);
		currencyCode = currencyCode.equals("") ? CONSTANTS.DEFAULT_CURRENCY : currencyCode;
		return getChangeCurrency(currencyCode);
		}

	// Show rates table when change base currency
	@RequestMapping(value = "/exchange_rates/code/{currencyCode}", method = RequestMethod.GET)
	public ModelAndView getChangeCurrency(@PathVariable String currencyCode) throws Exception{
		ModelAndView mv = new ModelAndView("exchange_rates");
		ExchangeRate baseExchangeRate = exchangeRateService.findByCode(currencyCode);

		List<ExchangeRate> rates = exchangeRateService.getRateListByBaseCurrency(baseExchangeRate);
		String currencyName = baseExchangeRate.getName();
		
		mv.addObject("currencyCode", currencyCode);
		mv.addObject("currencyName", currencyName);
		mv.addObject("ratesList", rates);
		return mv;
	}
}
